package com.glasses.business.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.test.espresso.core.deps.guava.eventbus.Subscribe;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.model.OSSException;
import com.facebook.drawee.view.SimpleDraweeView;
import com.glasses.business.R;
import com.glasses.business.activity.OrderCompanyActivity;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.entity.Address;
import com.glasses.business.entity.CheckMenu;
import com.glasses.business.entity.GlassMatch;
import com.glasses.business.entity.LightList;
import com.glasses.business.entity.PayInfo;
import com.glasses.business.entity.ProductDetail;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.AliUpLoadCallBack;
import com.glasses.business.utils.AliyunUploadUtils;
import com.glasses.business.utils.Camerautils_;
import com.glasses.business.utils.TimeUtils;
import com.glasses.business.utils.Tools;
import com.google.gson.Gson;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.pizidea.imagepicker.image.ImagesGridActivity;

import net.neiquan.applibrary.wight.AlertChooser;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.BitmapUtis;
import org.haitao.common.utils.CameraUtils;
import org.haitao.common.utils.FileUtils;
import org.haitao.common.utils.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import static android.R.attr.bitmap;
import static org.haitao.common.utils.CameraUtils.TAKE_PICTURE;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/7
 * Version：1.0
 */

public class MatchGlassFragment extends AppBaseFragment {
    @InjectView(R.id.glassUpLight)
    LinearLayout glassUpLight;
    @InjectView(R.id.glassHandLight)
    TextView glassHandLight;
    @InjectView(R.id.glassChangeLightRv)
    RelativeLayout glassChangeLightRv;
    @InjectView(R.id.glassChangeLight)
    TextView glassChangeLight;
    @InjectView(R.id.glassFrame)
    RelativeLayout glassFrame;
    @InjectView(R.id.glassPair)
    RelativeLayout glassPair;
    @InjectView(R.id.glassName)
    TextView glassName;
    @InjectView(R.id.glassPhone)
    TextView glassPhone;
    @InjectView(R.id.glassAddr)
    TextView glassAddr;
    @InjectView(R.id.glassAddrLL)
    LinearLayout glassAddrLL;
    @InjectView(R.id.glassMoney)
    TextView glassMoney;
    @InjectView(R.id.glassTime)
    TextView glassTime;
    @InjectView(R.id.glassBuy)
    TextView glassBuy;
    @InjectView(R.id.glassFrameImg)
    SimpleDraweeView glassFrameImg;
    @InjectView(R.id.glassFrameName)
    TextView glassFrameName;
    @InjectView(R.id.glassFrameDetail)
    TextView glassFrameDetail;
    @InjectView(R.id.glassFramePrice)
    TextView glassFramePrice;
    @InjectView(R.id.glassFrameLL)
    LinearLayout glassFrameLL;
    @InjectView(R.id.glassPairImg)
    SimpleDraweeView glassPairImg;
    @InjectView(R.id.glassPairName)
    TextView glassPairName;
    @InjectView(R.id.glassPairDetail)
    TextView glassPairDetail;
    @InjectView(R.id.glassPairPrice)
    TextView glassPairPrice;
    @InjectView(R.id.glassPairLL)
    LinearLayout glassPairLL;
    @InjectView(R.id.glassImg)
    SimpleDraweeView glassImg;
    @InjectView(R.id.glassOrderTime)
    TextView glassOrderTime;
    @InjectView(R.id.leftEyeSph)
    TextView leftEyeSph;
    @InjectView(R.id.leftEyeCyl)
    TextView leftEyeCyl;
    @InjectView(R.id.leftEyeAxl)
    TextView leftEyeAxl;
    @InjectView(R.id.rightEyeSph)
    TextView rightEyeSph;
    @InjectView(R.id.rightEyeCyl)
    TextView rightEyeCyl;
    @InjectView(R.id.rightEyeAxl)
    TextView rightEyeAxl;
    @InjectView(R.id.eyesPd)
    TextView eyesPd;
    @InjectView(R.id.glassOrderLL)
    LinearLayout glassOrderLL;
    @InjectView(R.id.userOldFrameImg)
    ImageView userOldFrameImg;
    @InjectView(R.id.userOldFrameLL)
    LinearLayout userOldFrameLL;
    @InjectView(R.id.oldFrameAddr)
    TextView oldFrameAddr;
    @InjectView(R.id.glassFrameOldLL)
    LinearLayout glassFrameOldLL;
    @InjectView(R.id.glassImgLL)
    LinearLayout glassImgLL;
    @InjectView(R.id.glassOrderTime_)
    TextView glassOrderTime_;
    private int type = 0;
    private String imgPath;
    private int productId;
    private GlassMatch glassMatch;
    private LightList checkMenu;
    private ProductDetail product0;
    private Address address;
    private int userMyProduct0 = 0;
    private int product1Id = 0;
    private int product0Id = 0;
    private GlassMatch.AddressBean addressBean;
    private GlassMatch.Product0Bean product0Bean;
    private int checkMenuId = 0;
    private String addressForChild;
    private double frameMoney = 0;
    private double pairMoney = 0;
    private int isUploadCheckMenu = 0;
    private Bitmap photo;
    private String srcPath;

    @Override
    public int getRootViewId() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return R.layout.fragment_match_glass;
    }

    @Subscribe
    public void onEventMainThread(BussEvent event) {
        if (event.getState() == BussEvent.After_Pay) {
            MyApplication.getInstance().manager.onBackPressed();
        } else if (event.getState() == BussEvent.Save_Light_Order) {
            isUploadCheckMenu = 1;
            CheckMenu checkMenu = (CheckMenu) event.getMessage();
            setGlassOrderViews(checkMenu);
            String content = new Gson().toJson(checkMenu);
            setViewVisible(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, View.GONE);
            upCheckMenu(content, 0);
        } else if (event.getState() == BussEvent.Check_Menu) {
            isUploadCheckMenu = 0;
            LightList lightList = (LightList) event.getMessage();
            if (lightList != null) {
                checkMenuId = lightList.getId();
                final String content = lightList.getContent();
                switch (lightList.getType()) {
                    case 0:
                        setViewVisible(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, View.GONE);
                        CheckMenu checkMenu = JSON.parseObject(content, CheckMenu.class);
                        setGlassOrderViews(checkMenu);
                        break;
                    case 1:
                        setViewVisible(View.VISIBLE, View.VISIBLE, View.GONE, View.GONE, View.GONE);
                        String imgPath = null;
                        try {
                            imgPath = new JSONObject(content).getString("imgPath");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        glassImg.setImageURI(imgPath);
                        glassOrderTime_.setText("更新时间:" + lightList.getUpdateTime());
                        break;
                }
            }
        } else if (event.getState() == BussEvent.Product1) {
            ProductDetail productDetail = ((ProductDetail) event.getMessage());
            if (productDetail == null) {
                glassPair.setVisibility(View.VISIBLE);
                glassPairLL.setVisibility(View.GONE);
            } else {
                product1Id = productDetail.getId();
                glassPair.setVisibility(View.GONE);
                glassPairLL.setVisibility(View.VISIBLE);
                glassPairImg.setImageURI(productDetail.getPicture());
                glassPairName.setText(productDetail.getName());
                pairMoney = productDetail.getPrice();
                glassPairPrice.setText("￥" + pairMoney);
                glassPairDetail.setVisibility(View.INVISIBLE);
                glassMoney.setText("价格:￥" + (frameMoney + pairMoney));
            }
        } else if (event.getState() == BussEvent.Product0) {
            product0 = ((ProductDetail) event.getMessage());
            if (product0 == null) {
                glassFrame.setVisibility(View.VISIBLE);
                glassFrameLL.setVisibility(View.GONE);
            } else {
                product0Id = product0.getId();
                glassFrame.setVisibility(View.GONE);
                glassFrameLL.setVisibility(View.VISIBLE);
                glassFrameImg.setImageURI(product0.getPicture());
                glassFrameName.setText(product0.getName());
                frameMoney = product0.getPrice();
                glassFramePrice.setText("￥" + frameMoney);
                glassPairDetail.setVisibility(View.VISIBLE);
                glassFrameDetail.setText(product0.getColor());
                glassMoney.setText("价格:￥" + (frameMoney + pairMoney));
            }
        } else if (event.getState() == BussEvent.Address) {
            address = ((Address) event.getMessage());
            glassAddr.setText(address.getAddress() + address.getDetailAddress());
            glassName.setText(address.getReceiver());
            glassPhone.setText(address.getPhone());
        }
    }

    private void setGlassOrderViews(CheckMenu checkMenu) {
        eyesPd.setText(checkMenu.getEyesPD());
        String leftAXL = checkMenu.getLeftAXL();
        if (!TextUtils.isEmpty(leftAXL)) {
            leftEyeAxl.setText(leftAXL);
        }
        leftEyeCyl.setText(checkMenu.getLeftCYL());
        leftEyeSph.setText(checkMenu.getLeftSPH());
        String rightAXL = checkMenu.getRightAXL();
        if (!TextUtils.isEmpty(rightAXL)) {
            rightEyeAxl.setText(rightAXL);
        }
        rightEyeCyl.setText(checkMenu.getRightCYL());
        rightEyeSph.setText(checkMenu.getRightSPH());
        glassOrderTime.setText("更新时间:" + TimeUtils.getTime(checkMenu.getUpdateTime()));
    }

    private void upCheckMenu(String content, int type) {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().checkMenu(content, type, new NetCallBack() {

            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                checkMenu = ((LightList) model.getModel());
                if (checkMenu != null) {
                    checkMenuId = checkMenu.getId();
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, LightList.class);
    }

    @Override
    public void setViews() {
        if (getArguments() != null) {
            productId = getArguments().getInt("productId");
            type = getArguments().getInt("type");
            switch (type) {
                case 0:
                    glassFrameOldLL.setVisibility(View.VISIBLE);
                    setTitleTv("配镜单");
                    break;
                case 1:
                    glassFrameOldLL.setVisibility(View.VISIBLE);
                    setTitleTv("配镜单");
                    break;
                case 2:
                    glassFrameOldLL.setVisibility(View.VISIBLE);
                    setTitleTv("配镜单");
                    break;
            }
        }
    }

    @Override
    public void initData() {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().orderInfo(productId, type, new NetCallBack() {

            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                glassMatch = ((GlassMatch) model.getModel());
                addressBean = glassMatch.getAddress();
                product0Bean = glassMatch.getProduct0();
                addressForChild = glassMatch.getAddressForChild();
                if (!TextUtils.isEmpty(addressForChild)) {
                    oldFrameAddr.setText("说明:请确认无损并将原镜架邮寄到" + addressForChild);
                }
//                if (glassMatch.getHaveBuy() == 0) {
//                    glassFrameOldLL.setVisibility(View.GONE);
//                } else {
//                    glassFrameOldLL.setVisibility(View.VISIBLE);
//                }
                GlassMatch.Product1Bean product1 = glassMatch.getProduct1();
                if (product0Bean == null) {
                    glassFrame.setVisibility(View.VISIBLE);
                    glassFrameLL.setVisibility(View.GONE);
                } else {
                    product0Id = product0Bean.getId();
                    glassFrame.setVisibility(View.GONE);
                    glassFrameLL.setVisibility(View.VISIBLE);
                    glassFrameImg.setImageURI(product0Bean.getPicture());
                    glassFrameName.setText(product0Bean.getName());
                    frameMoney = product0Bean.getPrice();
                    glassFramePrice.setText("￥" + frameMoney);
                    List<GlassMatch.Product0Bean.AttributuTypeBean> attributuType = product0Bean.getAttributuType();
                    StringBuilder sb = new StringBuilder();
                    if (attributuType != null && attributuType.size() > 0) {
                        for (int i = 0; i < attributuType.size(); i++) {
                            GlassMatch.Product0Bean.AttributuTypeBean attributuTypeBean = attributuType.get(i);
                            sb.append(attributuTypeBean.getAttributuType() + ":" + attributuTypeBean.getAttributuValue() + "     ");
                        }
                        glassFrameDetail.setVisibility(View.VISIBLE);
                        glassFrameDetail.setText(sb.toString());
                    } else {
                        glassFrameDetail.setVisibility(View.INVISIBLE);
                    }
                }
                if (product1 == null) {
                    glassPair.setVisibility(View.VISIBLE);
                    glassPairLL.setVisibility(View.GONE);
                } else {
                    product1Id = product1.getId();
                    glassPair.setVisibility(View.GONE);
                    glassPairLL.setVisibility(View.VISIBLE);
                    glassPairImg.setImageURI(product1.getPicture());
                    glassPairName.setText(product1.getName());
                    pairMoney = product1.getPrice();
                    glassPairPrice.setText("￥" + pairMoney);
                    List<GlassMatch.Product1Bean.AttributuTypeBeanX> attributuType = product1.getAttributuType();
                    StringBuilder sb = new StringBuilder();
                    if (attributuType != null && attributuType.size() > 0) {
                        for (int i = 0; i < attributuType.size(); i++) {
                            GlassMatch.Product1Bean.AttributuTypeBeanX attributuTypeBeanX = attributuType.get(i);
                            sb.append(attributuTypeBeanX.getAttributuType() + ":" + attributuTypeBeanX.getAttributuValue() + "     ");
                        }
                        glassPairDetail.setVisibility(View.VISIBLE);
                        glassPairDetail.setText(sb.toString());
                    } else {
                        glassPairDetail.setVisibility(View.INVISIBLE);
                    }
                }
                if (addressBean != null) {
                    glassName.setText(addressBean.getReceiver());
                    glassPhone.setText(addressBean.getPhone());
                    glassAddr.setText(addressBean.getAddress());
                }
                glassMoney.setText("价格:￥" + (frameMoney + pairMoney));
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, GlassMatch.class);
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }


    @OnClick({R.id.glassFrameOldLL, R.id.glassFrameLL, R.id.glassPairLL, R.id.glassUpLight, R.id.glassHandLight, R.id.glassChangeLight, R.id.glassFrame, R.id.glassPair, R.id.glassAddrLL, R.id.glassBuy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.glassUpLight:
                showAlertChooser();
                break;
            case R.id.glassHandLight:
                open(new HandLightFragment());
                break;
            case R.id.glassChangeLight:
                open(new LightOrderrFragment());
                break;
            case R.id.glassFrame:
                AppLog.e("===========glassFrame============");
                glassMoney.setText("价格:￥" + (frameMoney + pairMoney));
                userMyProduct0 = 0;
                userOldFrameImg.setImageResource(R.mipmap.icon_xz_copy);
                Bundle args = new Bundle();
                args.putInt("type", type == 1 ? 1 : 0);
                open(new GlassFrameFragment(), args);
                break;
            case R.id.glassPair:
                open(new GlassPairFragment());
                break;
            case R.id.glassAddrLL:
                open(new AddrFragment());
                break;
            case R.id.glassBuy:
                commitOrder();
                break;
            case R.id.glassFrameLL:
                AppLog.e("===========glassFrameLL============");
                glassMoney.setText("价格:￥" + (frameMoney + pairMoney));
                userMyProduct0 = 0;
                userOldFrameImg.setImageResource(R.mipmap.icon_xz_copy);
                Bundle args2 = new Bundle();
                args2.putInt("type", type == 1 ? 1 : 0);
                open(new GlassFrameFragment(), args2);
                break;
            case R.id.glassPairLL:
                if (type != 2) {
                    open(new GlassPairFragment());
                }
                break;
            case R.id.glassFrameOldLL:
                glassMoney.setText("价格:￥" + pairMoney);
                userMyProduct0 = 1;
                userOldFrameImg.setImageResource(R.mipmap.icon_xztb);
                glassFrame.setVisibility(View.VISIBLE);
                glassFrameLL.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(addressForChild)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("addressForChild", addressForChild);
                    open(new OldFrameFragment(), bundle);
                }
                break;
        }
    }

    private void commitOrder() {
        if (checkMenuId == 0) {
            ToastUtil.shortShowToast("请先选择或上传验光单...");
        } else if (product0Id == 0 && userMyProduct0 == 0) {
            ToastUtil.shortShowToast("请先选择镜架...");
        } else if (product1Id == 0) {
            ToastUtil.shortShowToast("请先选择镜片...");
        } else if (address == null && addressBean == null) {
            ToastUtil.shortShowToast("请先选择地址...");
        } else {
            String color = "";
            if (product0Bean != null) {
                List<GlassMatch.Product0Bean.AttributuTypeBean> attributuType = product0Bean.getAttributuType();
                if (attributuType != null && attributuType.size() > 0) {
                    GlassMatch.Product0Bean.AttributuTypeBean attributuTypeBean = attributuType.get(0);
                    color = attributuTypeBean.getAttributuValue();
                }
            }
            Tools.showDialog(getActivity());
            NetUtils.getInstance().commitOrder(productId, address != null ? address.getId() : addressBean.getId(), checkMenuId,
                    product0Id, product0 != null ? product0.getColor() : color,
                    product1Id, type, userMyProduct0, isUploadCheckMenu, new NetCallBack() {
                        @Override
                        public void onSuccess(String response, String mssage, ResultModel model) {
                            Tools.dismissWaitDialog();
                            ToastUtil.shortShowToast(mssage);
                            PayInfo payMoney = (PayInfo) model.getModel();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("payMoney", payMoney);
                            switch (payMoney.getIsHaveProduct0Information()) {
                                case 0:
                                    open(new OrderCompanyFragment(), bundle);
                                    break;
                                case 1:
                                    open(new PayFragment(), bundle);
                                    break;
                                default:
                                    break;
                            }
                        }

                        @Override
                        public void onFail(boolean dataError, int errorCode, String mssage) {
                            Tools.dismissWaitDialog();
                            ToastUtil.shortShowToast(mssage);
                        }
                    }, PayInfo.class);
        }
    }

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;

    private void showAlertChooser() {
        new AlertChooser.Builder(getActivity()).setTitle("选择图片").addItem("相机", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
//                Camerautils_.takePhoto(getActivity());
                chooser.dismiss();
//                AppLog.e("=================相机==================" + Camerautils_.photoPath);
//                startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                } else {
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, 1);
                }

            }
        }).addItem("相册", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                chooser.dismiss();
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                } else {
                    AndroidImagePicker.getInstance().setSelectMode(AndroidImagePicker.Select_Mode.MODE_SINGLE);
                    //AndroidImagePicker.Select_Mode.MODE_SINGLE单选模式
                    //AndroidImagePicker.Select_Mode.MODE_MULTI多选模式
                    //AndroidImagePicker.getInstance().setSelectLimit(MAX_NUM);//多选模式下  最多选多少张
                    AndroidImagePicker.getInstance().setShouldShowCamera(false);//相册里面是否显示拍照按钮
                    Intent intent = new Intent(getActivity(), ImagesGridActivity.class);
                    startActivityForResult(intent, CameraUtils.LOCAL_PICTURE);
                }
            }
        }).setNegativeItem("取消", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                chooser.dismiss();
            }
        }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(it, 1);
            } else {
                // Permission Denied
                ToastUtil.shortShowToast("拍照权限拒绝!");
            }
        }

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                AndroidImagePicker.getInstance().setSelectMode(AndroidImagePicker.Select_Mode.MODE_SINGLE);
                //AndroidImagePicker.Select_Mode.MODE_SINGLE单选模式
                //AndroidImagePicker.Select_Mode.MODE_MULTI多选模式
                //AndroidImagePicker.getInstance().setSelectLimit(MAX_NUM);//多选模式下  最多选多少张
                AndroidImagePicker.getInstance().setShouldShowCamera(false);//相册里面是否显示拍照按钮
                Intent intent = new Intent(getActivity(), ImagesGridActivity.class);
                startActivityForResult(intent, CameraUtils.LOCAL_PICTURE);
            } else {
                // Permission Denied
                ToastUtil.shortShowToast("获取相册权限拒绝!");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        AppLog.e("=========requestCode==========" + requestCode + "=============resultCode===========" + resultCode + "===========data=========" + data);
        if (requestCode == CameraUtils.LOCAL_PICTURE) {
            List<ImageItem> imageList = AndroidImagePicker.getInstance().getSelectedImages();
            if (imageList != null && imageList.size() > 0) {
                initAliyun(imageList.get(0).getPath());
//                mImageView.setImageURI("file://" + imageList.get(0).getPath());
            }
        } else if (requestCode == TAKE_PICTURE) {
//            initAliyun(CameraUtils.photoPath);
//            mImageView.setImageURI("file://" + CameraUtils.photoPath);
            if (data != null) {
                Bundle extras = data.getExtras();
                Bitmap b = (Bitmap) extras.get("data");
                String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                String fileNmae = Environment.getExternalStorageDirectory().toString() + File.separator + "dong/image/" + name + ".jpg";
                srcPath = fileNmae;
                System.out.println(srcPath + "----------保存路径1");
                File myCaptureFile = new File(fileNmae);
                try {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        if (!myCaptureFile.getParentFile().exists()) {
                            myCaptureFile.getParentFile().mkdirs();
                        }
                        BufferedOutputStream bos;
                        bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                        b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                        bos.flush();
                        bos.close();
                        initAliyun(srcPath);
                    } else {
                        ToastUtil.shortShowToast("保存失败，SD卡无效");
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void setViewVisible(int glassImgVisible, int glassChangeVisible, int glassOrderVisible, int glassHandleVisible, int glassUpVisible) {
        glassImgLL.setVisibility(glassImgVisible);
        glassChangeLightRv.setVisibility(glassChangeVisible);
        glassOrderLL.setVisibility(glassOrderVisible);
        glassHandLight.setVisibility(glassHandleVisible);
        glassUpLight.setVisibility(glassUpVisible);
    }

    private void initAliyun(final String path) {
        Tools.showWaitDialog(getContext(), "请稍后...");
        BitmapUtis.compress(path, 800, 600, new BitmapUtis.CompressCallback() {

            @Override
            public void onsucces(String s) {
                AliyunUploadUtils.getInstance(getActivity()).uploadPhoto(s, new AliUpLoadCallBack() {

                    @Override
                    public void onSuccess(String RootPath, String bucket, String fileName) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast("上传图片成功！");
                        isUploadCheckMenu = 1;
                        imgPath = RootPath + fileName;
                        glassImg.setImageURI(imgPath);
                        setViewVisible(View.VISIBLE, View.VISIBLE, View.GONE, View.GONE, View.GONE);
                        glassOrderTime_.setText("更新时间:" + TimeUtils.getTime(System.currentTimeMillis()));
                        upCheckMenu(imgPath, 1);
                    }

                    @Override
                    public void onFailure(String objectKey, OSSException ossException) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast("上传图片到服务器失败...请重新尝试");
                    }
                });
            }

            @Override
            public void onfail() {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast("图片太大或者已损坏，请重新选择图片");
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        EventBus.getDefault().unregister(this);
    }
}
